'use client'
import React, { useRef, useEffect, useState } from 'react';

// 定义网格配置的类型接口
interface GridConfig {
  cellSize: number;
  lineWidth: number;
  baseHue: number;
  hueRange: number;
  baseLightness: number;
  opacity: number;
  animationSpeed: number;
}

// 定义组件属性的类型接口
interface GradientGridBackgroundProps {
  width?: number;
  height?: number;
  config?: Partial<GridConfig>; // 允许部分配置覆盖默认值
}

const GradientGridBackground: React.FC<GradientGridBackgroundProps> = ({
  width,
  height,
  config: customConfig,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [mousePosition, setMousePosition] = useState<{ x: number; y: number }>({ x: 0, y: 0 });
  
  // 合并默认配置和自定义配置
  const gridConfig: GridConfig = {
    cellSize: 30,
    lineWidth: 1,
    baseHue: 200,
    hueRange: 60,
    baseLightness: 70,
    opacity: 0.8,
    animationSpeed: 0.05,
    ...customConfig,
  };

  // 处理鼠标移动事件的类型化函数
  const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {
    const canvas = canvasRef.current;
    if (canvas) {
      const rect = canvas.getBoundingClientRect();
      setMousePosition({
        x: e.clientX - rect.left,
        y: e.clientY - rect.top,
      });
    }
  };

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return; // 确保获取到3D上下文

    // 设置Canvas尺寸
    const updateCanvasSize = () => {
      canvas.width = width || window.innerWidth;
      canvas.height = height || window.innerHeight;
    };
    updateCanvasSize();

    let animationFrameId: number;
    let time = 0;

    // 绘制网格函数
    const drawGrid = () => {
      time += gridConfig.animationSpeed;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      
      const cols = Math.ceil(canvas.width / gridConfig.cellSize) + 1;
      const rows = Math.ceil(canvas.height / gridConfig.cellSize) + 1;
      
      // 绘制垂直线
      for (let col = 0; col < cols; col++) {
        const x = col * gridConfig.cellSize;
        
        // 计算动态色调和亮度（使用三角函数实现平滑变化）
        const hue = gridConfig.baseHue + 
                  Math.sin(col * 0.5 + time) * gridConfig.hueRange / 2 +
                  (mousePosition.x - x) * 0.05;
        
        const lightness = gridConfig.baseLightness + 
                        Math.cos(col * 0.3 + time * 1.2) * 10 +
                        Math.sin((mousePosition.y / canvas.height) * 5) * 5;
        
        // 确保色调在0-360范围内，亮度在0-100范围内
        const clampedHue = ((hue % 360) + 360) % 360;
        const clampedLightness = Math.max(0, Math.min(100, lightness));
        
        ctx.strokeStyle = `hsla(${clampedHue}, 70%, ${clampedLightness}%, ${gridConfig.opacity})`;
        ctx.lineWidth = gridConfig.lineWidth;
        
        ctx.beginPath();
        ctx.moveTo(x, 0);
        ctx.lineTo(x, canvas.height);
        ctx.stroke();
      }
      
      // 绘制水平线
      for (let row = 0; row < rows; row++) {
        const y = row * gridConfig.cellSize;
        
        const hue = gridConfig.baseHue + 
                  Math.cos(row * 0.5 + time * 0.8) * gridConfig.hueRange / 2 +
                  (mousePosition.y - y) * 0.05;
        
        const lightness = gridConfig.baseLightness + 
                        Math.sin(row * 0.3 + time * 1.5) * 10 +
                        Math.cos((mousePosition.x / canvas.width) * 5) * 5;
        
        const clampedHue = ((hue % 360) + 360) % 360;
        const clampedLightness = Math.max(0, Math.min(100, lightness));
        
        ctx.strokeStyle = `hsla(${clampedHue}, 70%, ${clampedLightness}%, ${gridConfig.opacity})`;
        ctx.lineWidth = gridConfig.lineWidth;
        
        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(canvas.width, y);
        ctx.stroke();
      }
      
      animationFrameId = requestAnimationFrame(drawGrid);
    };

    // 开始动画
    drawGrid();
    
    // 窗口大小变化处理
    const handleResize = () => {
      updateCanvasSize();
    };
    
    window.addEventListener('resize', handleResize);
    
    // 清理函数
    return () => {
      cancelAnimationFrame(animationFrameId);
      window.removeEventListener('resize', handleResize);
    };
  }, [width, height, gridConfig]);

  return (
    <canvas
      ref={canvasRef}
      onMouseMove={handleMouseMove}
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        zIndex: 0,
        width: '30%',
        height: '30%',
      }}
      aria-hidden="true" // 告知屏幕阅读器此元素为装饰性，无需读取
    />
  );
};

export default GradientGridBackground;
